<template>
<!--  菜品管理页-->
  <div style="background-color:#fff;padding:10px 20px;">
    <span style="line-height:60px;font-size:20px;">菜品管理</span>
  </div>
<!--  菜品数据搜索卡片-->
  <el-card style="margin:20px;height: 70px;">
    <el-form :inline="true">
      <el-form-item label="菜品名称">
        <el-input tyle="width:100px;" v-model="searchDishFrom.name" placeholder="请输入菜品名称"></el-input>
      </el-form-item>
      <el-form-item label="分店名称">
        <el-select v-model="searchDishFrom.branchId" @change="getDishTypeById(searchDishFrom.branchId)" style="width:150px;" placeholder="请选择分店">
          <el-option v-for="item in branchOptions"
          :label="item.name" :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="菜品所属菜系">
        <el-select v-model="searchDishFrom.typeId" style="width:150px;" placeholder="请选择菜品所属菜系">
        <el-option v-for="item in dishTypeOptions"
                   :label="item.name" :value="item.id"
        >
        </el-option>
      </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button @click="loadDishData" type="primary">搜索</el-button>
      </el-form-item>
    </el-form>
  </el-card>
<!--  菜品列表页-->
  <el-card style="margin:20px;">
    <div style="margin:10px 0px 40px 10px;">
      菜系列表
      <el-button type="primary" style="float: right;margin-top:-3px;" @click="beforeAddDish" >新增菜品</el-button>
    </div>
    <el-table :data="getDishArr">
      <el-table-column type="index" label="编号" width="80" align="center"/>
      <el-table-column prop="name" label="菜品名称" align="center"/>
      <el-table-column prop="price" label="菜品价格" align="center"/>
      <el-table-column prop="typeId" label="菜品类型" :formatter="typeRoleTable" align="center"/>
      <el-table-column prop="branchId" label="分店编号" :formatter="formatRoleTable" align="center"></el-table-column>
      <el-table-column prop="status" label="菜品状态" align="center">
        <template #default="scope">
          <el-switch active-value="0" inactive-value="1" v-model="scope.row.status" @change="changeStatus(scope.row.id,scope.row.status)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="菜品描述" align="center" show-overflow-tooltip="true"/>
      <el-table-column prop="createTime" label="创建时间" align="center"/>
      <el-table-column label="操作" align="center" width="170px">
        <template #default="scope" >
          <el-button link type="success" size="small" @click="detailsDish(scope.row.id)" >查看详情</el-button>
          <el-button link type="primary" size="small" @click="editDish(scope.row.id,scope)" >编辑</el-button>
          <el-button link type="danger" size="small" @click="deleteDish(scope.row.id,scope.row.imgUrl)">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
  </el-card>
<!--  新增菜品弹窗-->
  <el-dialog :title="dialogTitle" v-model="dialogDish" :before-close="handleClose" style="width:1000px;padding:40px;">
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="菜品名称">
            <el-input v-model="addDishFrom.name" placeholder="请输入菜品名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="菜品价格">
            <el-input v-model="addDishFrom.price" placeholder="请输入菜品价格">
              <template #append>元</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="所属分店">
            <el-select v-model="addDishFrom.branchId" @change="getDishTypeById(addDishFrom.branchId)">
              <el-option v-for="item in branchOptions"
                         :label="item.name" :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="菜品所属菜系">
            <el-select v-model="addDishFrom.typeId" placeholder="请选择菜品菜系">
              <el-option v-for="item in dishTypeOptions"
              :label="item.name" :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="菜品描述">
            <el-input v-model="addDishFrom.description" placeholder="请输入菜品描述"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="菜品状态">
            <el-radio-group v-model="addDishFrom.status">
              <el-radio border label="启用" value="0" style="margin:0;"></el-radio>
              <el-radio border label="禁用" value="1"></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12" v-if="addDishFrom.id!=null">
          <template #default>
            <el-form-item label="菜品图片">
              <img :src="BASE_URL+addDishFrom.imgUrl" width="150px"/>
            </el-form-item>
          </template>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="imgTitleName">
            <el-upload
                v-model:file-list="fileList"
                v-model:action="actionUrl"
                name="file"
                limit="1"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
            >
              <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" width="100px"/>
              </el-dialog>
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveAddDishFrom">确定</el-button>
    </template>
  </el-dialog>
<!--  菜品详情页-->
  <el-dialog title="菜品详情" v-model="dialogDetails" :before-close="handleClose" style="width:1000px;padding:40px;">
    <el-descriptions direction="horizontal" :column="2" border>
      <el-descriptions-item label="菜品名称">{{addDishFrom.name}}</el-descriptions-item>
      <el-descriptions-item label="菜品价格">{{addDishFrom.price}}</el-descriptions-item>
      <el-descriptions-item label="菜品菜系">{{addDishFrom.typeId}}</el-descriptions-item>
      <el-descriptions-item label="所属分店">{{addDishFrom.branchId}}</el-descriptions-item>
      <el-descriptions-item label="菜品状态">{{addDishFrom.status}}</el-descriptions-item>
      <el-descriptions-item label="菜品描述">{{addDishFrom.description}}</el-descriptions-item>
      <el-descriptions-item label="菜品图片">
        <img :src="BASE_URL+addDishFrom.imgUrl" width="100px"/>
      </el-descriptions-item>
    </el-descriptions>
  </el-dialog>


</template>

<script setup>

import {onMounted, ref} from "vue";
import qs from "qs";
import axios from "axios";
import {ElMessage} from "element-plus";

const dialogDish =ref(false)//显示新增菜品弹窗
const dialogDetails = ref(false)//显示菜品详情
const dialogTitle = ref('')
const imgTitleName = ref('请上传菜品图片')
//定义对象保存搜索条件
const searchDishFrom = ref({
  name:'',
  branchId:'',
  typeId:'',
})

//定义数组保存菜品数据
const getDishArr = ref([])

/* 点击"新增菜品"按钮,出弹窗+修改弹窗标题 */
const beforeAddDish = ()=>{
  dialogDish.value = true;
  dialogTitle.value = '新增菜品';
  imgTitleName.value = '请上传菜品图片';
}
//定义加载菜品信息的方法
const loadDishData = ()=>{
  let data = qs.stringify(searchDishFrom.value);
  axios.get(BASE_URL + '/v1/dish/select?'+data)
      .then((response) => {
        if (response.data.code == 2000){
          getDishArr.value = response.data.data;
          // 清除搜索条件
          searchDishFrom.value = {};
          console.log(response.data.data)
        }else {
          ElMessage.error(response.data.msg);
        }
      })
}
// 定义保存所以菜品信息的数组
const dishOptions = ref([]);
const typeRoleTable = (row,column,cellValue,index)=>{
  if(!dishOptions.value){
    return cellValue;
  }
  for(let item of dishOptions.value){
    if(item.id==cellValue){
      cellValue = item.name;
    }
  }
  return cellValue;
};
// 定义保存所有分店数据的数组
const branchOptions = ref([]);
const formatRoleTable = (row,column,cellValue,index)=>{
  if(!branchOptions.value){
    return cellValue;
  }
  for(let item of branchOptions.value){
    if(item.id==cellValue){
      cellValue = item.name;
    }
  }
  return cellValue;
};

onMounted(()=>{
  loadDishData();
  getBranchs(branchOptions);
  // 加载所有的菜系的数据,回显菜品类型的选项
  getCookingTypes(dishOptions);
})
//定义重置按钮的方法
const resetSearch = ()=>{
  searchDishFrom.value = {};
  loadDishData();
  dishTypeOptions.value = [];
}
//定义对象用来保存新增菜品表单数据
const addDishFrom = ref({
  name:'',//菜品名称
  price:'',//菜品价格
  typeId:'',//菜品类型
  branchId:'',//分店编号
  status:'',//菜品状态
  description:'',//菜品描述
  imgUrl:''
})
//定义一个数组保存根据分店编号获取到的菜系的数据
const dishTypeOptions = ref([]);
//定义根据分店编号获取所有分店菜系的方法
const getDishTypeById = (branchId)=>{
  console.log(branchOptions.value)
  console.log("分店id:"+branchId);
  // 清空菜系的数据，每次选择重新加载
  dishTypeOptions.value = [];
  axios.get(BASE_URL + '/v1/dishType/select?branchId='+branchId)
      .then((response)=>{
        if (response.data.code == 2000){
          for (let i = 0; i < response.data.data.length; i++) {
            dishTypeOptions.value.push(response.data.data[i])

          }
          console.log(dishTypeOptions)
        }else {
          ElMessage.error(response.data.msg);
        }
      })
}
//定义保存新增菜品表单数据的方法
const saveAddDishFrom = ()=>{
  if (dialogTitle.value=='新增菜品'){
    if(fileList.value.length==0){
      ElMessage.error('请上传菜品图片!');
      return;
    }
  }else if (dialogTitle.value=='编辑菜品'){
    if (fileList.value.length!=0){
      // 将后端返回的图片地址的地址回显
      //fileList.value[0].response.data = addDishFrom.value.imgUrl ;
      // 获取之前的图片路径
      let imgUrl = addDishFrom.value.imgUrl;
      // 删除之前的图片
      //2.给后端发请求,删除图片
      axios.post(BASE_URL+'/v1/file/remove?imgUrl='+imgUrl)
          .then((response)=>{
            if (response.data.code===2000){
              ElMessage.success('已删除旧的图片!');
            }
          })

    }
  }
  //从upload图片上传组件中获取上传图片的路径 fileList.value[0]是第一个图片对象
  if (fileList.value[0]==null){
    // 将代表不对图片进行修改，此时应该不修改菜品的图片信息
    addDishFrom.value.imgUrl = '';
  }else{
    // 将上传的图片地址保存到表单中，此时应该修改菜品的图片信息
    addDishFrom.value.imgUrl = fileList.value[0].response.data;
    }

  let data = qs.stringify(addDishFrom.value);
  axios.post(BASE_URL + '/v1/dish/save',data)
      .then((response)=>{
        if (response.data.code == 2000){
          //关闭弹窗
          dialogDish.value = false;
          //清空图片组件内容
          fileList.value=[];
          //重新加载菜品列表
          loadDishData();
          addDishFrom.value = {};//清空表单数据
          ElMessage.success('保存成功!');
        }else {
          ElMessage.error(response.data.msg);
        }
      })
}
//定义修改菜品状态的方法
const changeStatus =(dishId,status)=>{
  axios.post(BASE_URL+'/v1/dish/update/status/'+dishId+'/'+status)
      .then((response)=>{
        if(response.data.code == 2000){
          ElMessage.success('修改状态成功!');
        }else{
          ElMessage.error(response.data.msg);
        }
      })
}
//定义编辑菜品的方法
const editDish = (id)=>{
  dialogTitle.value = '编辑菜品';
  imgTitleName.value = '修改菜品图片';
  dialogDish.value = true;
  //addDishFrom.value.imgUrl=scope.row.imgUrl
  // 查询回显数据
  axios.get(BASE_URL + '/v1/dish/select?id='+id)
      .then((response)=>{
        if (response.data.code == 2000){
          //将查询到的菜品数据回显到表单中
          addDishFrom.value = response.data.data[0];
          //此时为编辑菜品
          //将图片地址加入到（前端回显图片的数组）
          console.log(addDishFrom.value.imgUrl)
          // 回显对应分店的菜系
          getDishTypeById(addDishFrom.value.branchId);
          //fileList.value.push(BASE_URL+addDishFrom.value.imgUrl)
        }else {
          ElMessage.error(response.data.msg);
        }
      })

}
//查看菜品详情的方法
const detailsDish = (id)=>{
  dialogDetails.value = true;
  axios.get(BASE_URL + '/v1/dish/select?id='+id)
      .then((response)=>{
        if (response.data.code == 2000){
          //将查询到的菜品数据回显到表单中
          addDishFrom.value = response.data.data[0];
        }else {
          ElMessage.error(response.data.msg);
        }
      })
}
//定义关闭弹窗的方法
const handleClose = ()=>{
  if(confirm('您确认要关闭本窗口吗?')){
    //关闭弹窗,并清空双向绑定的表单数据
    dialogDish.value = false;
    dialogDetails.value=false
    addDishFrom.value = {};
    dishTypeOptions.value=[];
  }
}
/**图片上传相关代码开始**/
//前端回显图片数组
const fileList = ref([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);//控制图片预览窗口的显示与隐藏
//定义变量用来保存图片上传给哪个后端接口地址
const actionUrl = ref(BASE_URL + '/v1/file/upload');
//移除图片
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
  //1.得到要删除的图片路径 uploadFile就是我们要删除的那个图片文件对象
  let imgUrl = uploadFile.response.data;
  //2.给后端发请求,删除图片
  axios.post(BASE_URL + '/v1/file/remove?imgUrl=' + imgUrl)
      .then((response) => {
        if (response.data.code == 2000) {
          ElMessage.success('删除成功!');
        }
      })
}
//图片上传后预览
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  console.log(dialogImageUrl.value);
  dialogVisible.value = true;
  console.log(uploadFile);
  console.log(fileList.value[0].response.data);
}
/**图片上传相关代码结束**/
const deleteDish = (id,imgUrl)=>{
  if(confirm('您确认要删除该菜品吗?')){
    axios.post(BASE_URL + '/v1/dish/delete/'+id)
        .then((response)=>{
          if (response.data.code == 2000){
            //重新加载菜品列表
            loadDishData();
            ElMessage.success('删除成功!');
            //2.给后端发请求,删除图片
            axios.post(BASE_URL+'/v1/file/remove?imgUrl='+imgUrl)
                .then((response)=>{
                  if (response.data.code===2000){
                    //
                  }
                })
          }else {
            ElMessage.error(response.data.msg);
          }
        })
  }
}
</script>

<style scoped>
</style>